import axios, { AxiosResponse, AxiosRequestConfig, AxiosInstance, AxiosPromise } from 'axios'
import useUserStore from "../../src/store/userStore";
// 自定义axios config 参数
interface CUAxiosRequestConfig extends AxiosRequestConfig{
    noAuthed?:boolean,
    loading?:boolean
}
// 自定义axios config 参数
interface CUAxiosInstance extends AxiosInstance{
    (config: CUAxiosRequestConfig): AxiosPromise;
}

const service:CUAxiosInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASEURL + '',
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    }
})


service.interceptors.request.use(
    (config: CUAxiosRequestConfig) => {
        const { token } = useUserStore();
        let userToken = token || localStorage.getItem('token');
        if (userToken && !config.noAuthed) {
            config.headers['Authorization'] = 'Bearer ' + userToken //设置token
        }
        return config
    },
    (error: any) => {
        return Promise.resolve({
            code: 500,
            message: '访问出现错误',
            error
        })
    }
)

service.interceptors.response.use(
    async (response: AxiosResponse) => {
        const { status } = response;
        if (status === 200) {
            let res: any = response.data || {}
            const { code, message, data } = res;
            if (code === 0) {
                return data;
            } else {
                let win: any = window;
                // code为1代表操作失败,code为1002代表没有权限
                if (code === 1 || code === 1002) {
                    win.$message && win.$message.error(message ?? '操作失败');
                    return Promise.reject(message)
                }
                if (code === 401) {
                    // code为401代表后端设置授权过期， status为401代表jwt自动返回的过期
                    win.$message && win.$message.error('授权已过期');
                    const { LOGIN_OUT } = useUserStore();
                    LOGIN_OUT();
                    return Promise.reject(message)
                }
            }
        }
    },
    (error: any) => {
        if (error.response) {
            const { status, data } = error.response;
            const { message } = data;
            if (status === 401) {
                let win: any = window;
                win.$message && win.$message.error('授权已过期');
            } else if (status === 500) {
                let win: any = window;
                win.$message && win.$message.error('服务器出错了！');
            }
        }
        return Promise.reject(error.response)
    }
)

export default service
